package com.msb.bf;


import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author zhaoyi
 * @date 2020/3/30
 * 自定义实现一个基于AtomicReference的链表
 *  可以使用 AtomicStampedReference 带时间戳解决ABA问题222
 */
public class AtomicReferenceArray {

    private int[] ints;
    private AtomicReference<int[]> atomicReferenceNode;

    /**
     * 构建器中初始化AtomicReference
     *
     * @param ints
     */
    public AtomicReferenceArray(int[] ints) {
        this.ints = ints;
        this.atomicReferenceNode = new AtomicReference<>(ints);
    }

    public void atomic(int value) {
        //CAS 操作
        while (true) {
            int[] old = this.atomicReferenceNode.get();
            int[] newInts = new int[old.length + 1];
            for (int i = 0; i < newInts.length; i++) {
                if (i < old.length) {
                    newInts[i] = old[i];
                } else {
                    newInts[i] = value;
                }
            }
            if (this.atomicReferenceNode.compareAndSet(old, newInts)) {
                ints = newInts;
                break;
            }
        }
    }

    public void notAtomic(int value){
        int[] newInts = new int[ints.length + 1];
        for (int i = 0; i < newInts.length; i++) {
            if (i < ints.length) {
                newInts[i] = ints[i];
            } else {
                newInts[i] = value;
            }
        }
        ints = newInts;
    }

    public void printValues() {
        System.out.println("========长度 "+ints.length);
        //System.out.println(Arrays.toString(ints));
    }
}

